package drds.plus.executor.transaction;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.utils.AtomicNumberCreator;

import java.sql.SQLException;
import java.util.concurrent.locks.ReentrantLock;

public abstract class AbstractTransaction implements Transaction {

    protected final AtomicNumberCreator atomicNumberCreator = AtomicNumberCreator.getNewInstance();
    protected final Integer id = atomicNumberCreator.getIntegerNextNumber();
    protected final ReentrantLock lock = new ReentrantLock();
    protected ExecuteContext executeContext;
    private boolean closed;

    public AbstractTransaction(ExecuteContext executeContext) {
        super();
        this.executeContext = executeContext;
    }

    public void setExecuteContext(ExecuteContext executeContext) {
        this.executeContext = executeContext;

    }

    public long getId() {
        return id;
    }

    public void close() {
        this.closed = true;
    }

    public boolean isClosed() {
        lock.lock();
        try {
            return this.closed;
        } finally {
            lock.unlock();
        }
    }

    public void kill() throws SQLException {
        lock.lock();
        try {
            this.getConnectionHolder().kill();
        } finally {
            lock.unlock();
        }
    }

    public void cancel() throws SQLException {
        lock.lock();
        try {
            this.getConnectionHolder().cancel();
        } finally {
            lock.unlock();
        }
    }

}
